package com.qingyun.form.items

import android.view.View
import com.qingyun.form.R
import com.qingyun.form.base.FormType
import com.qingyun.form.base.FormViewHolder
import com.qingyun.form.dialog.FormSelectDialogFragment
import com.qingyun.form.provider.FormDataProvider
import com.qingyun.form.entity.FormSelectItem
import com.qingyun.form.listener.FormSelectChangedListener

class SelectFormItem(
    private val provider: FormDataProvider,
    label: String,
    name: String,
    value: String?,
    required: Boolean = false,
) : BaseFormItem(label, name, value), FormSelectChangedListener {
    override val formType: FormType
        get() = FormType.Select
    override val layoutId: Int
        get() = R.layout.form_item_select
    override var hint: String? = null
        get() = if (field == null) "请选择" else field
    var dialogTitle: String? = null
        get() = if (field == null) "请选择$label" else field
    var filter: String? = null
    var enableFullPath: Boolean = true

    init {
        this.required = required
    }

    override fun onBindViewEvent(holder: FormViewHolder) {
        super.onBindViewEvent(holder)
        holder.itemView.setOnClickListener(this::onItemClick)
    }

    override fun onUnBindViewEvent(holder: FormViewHolder) {
        super.onUnBindViewEvent(holder)
        holder.itemView.setOnClickListener(null)
    }

    override fun onBindViewHolder(holder: FormViewHolder) {
        this.provider.filter = this.filter
        val label = this.value?.let {
            if (enableFullPath) {
                provider.getItem(it)?.let { item ->
                    provider.getFullLabel(item)
                }
            } else {
                provider.getItemLabel(it)
            }
        }
        holder.setVisibility(R.id.tvValue, true)
        holder.setText(R.id.tvValue, label)
    }

    private fun onItemClick(v: View) {
        val manager = fragmentManager ?: return
        FormSelectDialogFragment.show(manager, this.value, this.dialogTitle).apply {
            this.provider = this@SelectFormItem.provider
            this.listener = this@SelectFormItem
            this.provider.filter = this@SelectFormItem.filter
        }
    }

    override fun onFormSelectChanged(item: FormSelectItem) {
        val newValue = provider.getItemValue(item.value)
        if (newValue != this.value) {
            onValueChanged(newValue, true)
        }
    }
}